//
//  ScannerViewController.m
//  specialine
//
//  Created by 往返网络 on 17/2/15.
//  Copyright © 2017年 com. All rights reserved.
//

#import "ScannerViewController.h"
#import "PureLayout.h"
#import "SaoWebViewController.h"

@interface ScannerViewController ()

@end

@implementation ScannerViewController{

    UIButton * erwemabtn; //二维码扫描
    
    UIButton * tiaoxingmabtn;  //条形码扫描

    int saomiaotype; // (为1  －－ 二维码扫描， 2 为条形码扫描)

    UILabel * labIntroudction; //扫描类型提示信息
    
   // UIButton * returnbtn; //返回按钮
    
}

- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    
    self.navigationItem.title = @"扫一扫";
    
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.translucent = NO;
    
    self.tabBarController.tabBar.hidden  = YES;
    
    float fontsize = 17;
    
    fontsize = SCREEN_H < 667 ? 15 : 19;
    
    if (SCREEN_H == 667) {
        
        fontsize = 17;
    }

    
    //设置导航条
    self.navigationController.navigationBar.barTintColor = COLORRGBA(7, 24, 57, 1);
    
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName :[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:17]};

    UIButton * returnbtn1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100.0/W_BASE*SCREEN_W, 88.0/H_BASE*SCREEN_H)];
    
    returnbtn1.titleLabel.font = [UIFont fontWithName:@"iconfont" size:fontsize + 5];
    
    [returnbtn1 setTitle:@"\U0000e697" forState:UIControlStateNormal];
    
    [returnbtn1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    UIBarButtonItem * item1 = [[UIBarButtonItem alloc]initWithCustomView:returnbtn1];
    
    self.navigationItem.leftBarButtonItem = item1;
    
    [returnbtn1 setTitleEdgeInsets:UIEdgeInsetsMake(0,0 , 0, 60.0/W_BASE*SCREEN_W)];
    
    [returnbtn1 addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    


    if (hasCameraRight) {
        
        if (_session && ![_session isRunning]) {
            
            [_session startRunning];
            
        }
        //点击扫描类型后，再进行扫描动画开始

     //   timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
        
    }
    

}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
//    self.tabBarController.tabBar.hidden = YES
    
    self.tabBarController.tabBar.hidden = NO;

    
}

- (void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    
    [timer invalidate];//停止扫描

    
}

- (void)viewDidLoad {
    
    // Do any additional setup after loading the view.
    [super viewDidLoad];
    
    self.title = @"扫一扫";
    
    self.view.backgroundColor = COLORRGBA(153, 153, 153, 1);
    //
    //默认为二维码扫描
    
    saomiaotype = 1;
    
    NSString *mediaType = AVMediaTypeVideo;
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"没有相机权限" message:@"请去设置-隐私-相机中对专线通授权" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popViewControllerAnimated:YES];
        }];
        [alertController addAction:okAction];
        
        hasCameraRight = NO;
        
        return;
        
    }
    hasCameraRight = YES;
    
    imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 0.8 * self.view.frame.size.width, 0.8 * self.view.frame.size.width)];
    imageView.image = [UIImage imageNamed:@"contact_scanframe"];
    [self.view addSubview:imageView];
    [imageView autoAlignAxis:ALAxisVertical toSameAxisOfView:self.view];
    [imageView autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:100];
    [imageView autoSetDimensionsToSize:CGSizeMake(0.8 * self.view.frame.size.width, 0.8 * self.view.frame.size.width)];
    
    labIntroudction= [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 290, 30)];
    labIntroudction.backgroundColor = [UIColor clearColor];
    labIntroudction.textColor=[UIColor whiteColor];
    labIntroudction.textAlignment = NSTextAlignmentCenter;
    labIntroudction.text=@"将取景框对准二维码，即自动扫描";
    [self.view addSubview:labIntroudction];
    [labIntroudction autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:imageView];
    [labIntroudction autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:imageView];
    [labIntroudction autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:imageView withOffset:8];
    
    
    
    upOrdown = NO;
    num =0;
    _line = [[UIImageView alloc] initWithFrame:CGRectMake(50, 110, 220, 2)];
    _line.image = [UIImage imageNamed:@"line"];
    [self.view addSubview:_line];
    [_line autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:imageView withOffset:40];
    [_line autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:imageView withOffset:-40];
    [_line autoSetDimension:ALDimensionHeight toSize:2];
    [_line autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:imageView withOffset:10];
    
    
    UIView * backview = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_H - SCREEN_W/4.0, SCREEN_W,SCREEN_H * 0.25 )];
    backview.backgroundColor = COLORRGBA(24, 19, 18, 1);
    
    [self.view addSubview:backview];
    
    erwemabtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_W / 5.0, SCREEN_H - SCREEN_W/5.0-5, SCREEN_W / 5.0, SCREEN_W/5.0-10)];
    
    erwemabtn.backgroundColor = COLORRGBA(31, 188, 141, 1);
    
   // [self.view addSubview:erwemabtn];
    
    [erwemabtn setTitle:@"二维码" forState:UIControlStateNormal];
    
  
    tiaoxingmabtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_W / 5.0*3, CGRectGetMinY(erwemabtn.frame), CGRectGetWidth(erwemabtn.frame), CGRectGetHeight(erwemabtn.frame))];
    
    tiaoxingmabtn.backgroundColor = COLORRGBA(31, 188, 141, 1);
    
  //  [self.view addSubview:tiaoxingmabtn];
    
    [tiaoxingmabtn setTitle:@"条形码" forState:UIControlStateNormal];

    erwemabtn.tag = 1000;
    
    tiaoxingmabtn.tag = 2000;
    
    
    
    [erwemabtn addTarget:self action:@selector(changeOuputType:) forControlEvents:UIControlEventTouchUpInside];
    
    [tiaoxingmabtn addTarget:self action:@selector(changeOuputType:) forControlEvents:UIControlEventTouchUpInside];


    
    
    //开始扫描
    
    [self setupCamera];
}

#pragma mark - -- - - -更改扫描类型 -  -- - -- - -- - - -
- (void)changeOuputType:(UIButton *)btn{


    [_session stopRunning];
    
    if (btn.tag == 1000) {
        
        //更改扫描类型为二维码
        
        NSLog(@"扫描二维码");
        
        saomiaotype = 1;
        
        //扫描动画开始
        
        labIntroudction.text=@"将取景框对准二维码，即自动扫描";

        timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
        
        [self setupCamera];

        
    }
    else{
    
     //更改扫描类型为条形码
    
        NSLog(@"扫描条形码");
        
        saomiaotype = 2;
        
        labIntroudction.text=@"将取景框对准条形码，即自动扫描";

        //扫描动画开始
        
        timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
        
        [self setupCamera];

    }




}
-(void)animation1
{
    if (upOrdown == NO) {
        num ++;
        _line.frame = CGRectMake(CGRectGetMinX(_line.frame), 110+2*num, CGRectGetWidth(_line.frame), CGRectGetHeight(_line.frame));
        if (2 * num == CGRectGetHeight(imageView.frame) - 20) {
            upOrdown = YES;
        }
    }
    else {
        num --;
        _line.frame = CGRectMake(CGRectGetMinX(_line.frame), 110+2*num, CGRectGetWidth(_line.frame), CGRectGetHeight(_line.frame));
        if (num == 0) {
            upOrdown = NO;
        }
    }
    
    
}
//
//- (BOOL)navigationShouldPopOnBackButton
//{
//    
//    NSLog(@"return btn");
//    
//    [timer invalidate];
//    
//    return YES;
//    
//}



- (void)setupCamera
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 耗时的操作
        // Device
        _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        
        // Input
        _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
        
        // Output
        _output = [[AVCaptureMetadataOutput alloc]init];
        //    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        
        // Session
        _session = [[AVCaptureSession alloc]init];
        [_session setSessionPreset:AVCaptureSessionPresetHigh];
        if ([_session canAddInput:self.input])
        {
            [_session addInput:self.input];
        }
        
        if ([_session canAddOutput:self.output])
        {
            [_session addOutput:self.output];
        }
        
        // 条码类型 AVMetadataObjectTypeQRCode
        
        if (saomiaotype == 1) {
            
            NSLog(@"扫描类型为二维码");
            _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];

        }
        else if (saomiaotype == 2){
        
            NSLog(@"扫描类型为条形码");
            _output.metadataObjectTypes=@[AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];

        
        }
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // 更新界面
            // Preview
            _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
            _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
            //    _preview.frame =CGRectMake(20,110,280,280);
            _preview.frame = self.view.bounds;
            [self.view.layer insertSublayer:self.preview atIndex:0];
            // Start
            [_session startRunning];
            
            
        });
    });
}

#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    
    NSString *stringValue;
    
    if ([metadataObjects count] >0)
    {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        
        //输出扫描字符串
        NSLog(@"扫描到的字符串为 %@",metadataObject.stringValue);
        [_session stopRunning];
        [timer invalidate];
        NSLog(@"%@",stringValue);
        
        SaoWebViewController * webview = [[SaoWebViewController alloc]init];
        
        webview.saomiaotype = saomiaotype;
        
        webview.urlstring = stringValue;
        
        [self.navigationController pushViewController:webview animated:YES];
        
        if (stringValue.length > 0) {
            
            //            NSString *url = [NSURL URLWithString:@"html/judgement.html" relativeToURL:[ZXApiClient sharedClient].baseURL].absoluteString;
            //
            //            if ([stringValue hasPrefix:url]) {
            //                NSArray *arr = [stringValue componentsSeparatedByString:@"?"];
            //                if (arr.count > 1) {
            //                    NSString *uid = [[arr objectAtIndex:1] substringFromIndex:4];
            //
            //                    if (uid.integerValue == GLOBAL_UID) {
            //                        ZXMyProfileViewController *vc = [ZXMyProfileViewController viewControllerFromStoryboard];
            //                        [self.navigationController pushViewController:vc animated:YES];
            //                    } else {
            //                        ZXUserProfileViewController *vc = [ZXUserProfileViewController viewControllerFromStoryboard];
            //                        vc.uid = uid.integerValue;
            //                        [self.navigationController pushViewController:vc animated:YES];
            //                    }
            //                }
            //            }
            //            else if ([stringValue hasPrefix:[NSString stringWithFormat:@"%@qrcodelogin?qrcodeId=",@"http://www.aierbon.com/"]]) {
            //                NSString *qrcodeId = [[stringValue componentsSeparatedByString:@"="] lastObject];
            //                ZXLoginBackendViewController *vc = [ZXLoginBackendViewController viewControllerFromStoryboard];
            //                vc.qrcodeid = qrcodeId;
            //                [self.navigationController pushViewController:vc animated:YES];
            //            }
            //            else {
            
            
            
            
          //  [self.navigationController popViewControllerAnimated:YES];
            //                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:stringValue]];
            //            }
        }
    }
    
}

- (void)enterClick:(UIButton *)btn{


    [self.navigationController popViewControllerAnimated:YES];
    

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
